﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net.Http;
using Newtonsoft.Json;
using System.Net;
using System.IO;

namespace DeepSeekDemo
{
    // 国家互联网超算中心DeepSeek API接口(可免费试用，但模型非最新)
    //https://www.scnet.cn/ac/openapi/doc/2.0/moduleapi/api/chat.html

    public class DeepSeekChatService2
    {
        private const string API_KEY = "sk-Mjg5LTExNDEwNzMzMDg0LTE3NDYwOTkyNzgyOTc";               // 修改为自己申请的KEY值： https://www.scnet.cn/ui/llm/apikeys
        private const string API_ENDPOINT = "https://api.scnet.cn/api/llm/v1/chat/completions";
        //private const string CHAT_MODEL = "DeepSeek-R1-Distill-Qwen-7B";    // 根据实际模型名称修改 https://www.scnet.cn/ac/openapi/doc/2.0/moduleapi/tutorial/modulefee.html
        private const string CHAT_MODEL = "DeepSeek-R1-Distill-Qwen-32B";   
        

        private static readonly HttpClient _httpClient = new HttpClient();
        public async Task<string> ChatAsync(string userMessage)
        {
            try
            {
                // 构造对话请求体
                var requestData = new
                {
                    model = CHAT_MODEL,
                    messages = new[]
                    {
                        new { role = "user", content = userMessage }
                    },
                    temperature = 1,
                    max_tokens = 4096
                };

                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                string content = JsonConvert.SerializeObject(requestData);

                //string response0 = Request(API_ENDPOINT, API_KEY, content);
                //return response0;


                // 设置认证头
                _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", API_KEY);


                // 发送请求
                var response = await _httpClient.PostAsync(
                    API_ENDPOINT,
                    new StringContent(content, Encoding.UTF8, "application/json")
                    );

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    var jsonResponse = await response.Content.ReadAsStringAsync();

                    try
                    {
                        var result = JsonConvert.DeserializeObject<ChatResponse>(jsonResponse);
                        return result.choices[0].message.content;
                    }
                    catch { return jsonResponse; }
                }
                else
                {
                    return "API错误: " + response.StatusCode + "\r\n" + response.ToString();
                }
            }
            catch (Exception ex)
            {
                return "请求异常: " + ex.Message + "\r\n" + ex.ToString();
            }
        }

        // 响应模型
        public class ChatResponse
        {
            public Choice[] choices { get; set; }

            public class Choice
            {
                public Message message { get; set; }
            }

            public class Message
            {
                public string role { get; set; }
                public string content { get; set; }
            }
        }


        //POST / HTTP/1.1
        //Content-Type: application/json;charset=UTF-8
        //Authorization: Bearer sk-b02eda3a6fc94032a9626427d0c1a4e0
        //Host: 127.0.0.1:30001
        //Content-Length: 120
        //Expect: 100-continue
        //{"model":"deepseek-chat","messages":[{"role":"user","content":"测试"}],"temperature":0.7,"max_tokens":500,"stream":false}


        public string ChatAsync2(string userMessage)
        {
            try
            {
                // 构造对话请求体
                var requestData = new
                {
                    model = CHAT_MODEL,
                    messages = new[]
                    {
                        new { role = "user", content = userMessage }
                    },
                    temperature = 1,
                    max_tokens = 500
                };

                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                string content = JsonConvert.SerializeObject(requestData);

                string response0 = Request(API_ENDPOINT, API_KEY, content);
                return response0;
            }
            catch (Exception ex)
            {
                return "请求异常: " + ex.Message + "\r\n" + ex.ToString();
            }
        }

        /// <summary>
        /// 执行http请求
        /// </summary>
        /// <param name="url">请求网址</param>
        /// <param name="postData">需要通过post提交的数据</param>
        /// <returns>返回服务器端响应结果</returns>
        public static string Request(string url, string API_KEY, string postData = null)
        {
            string result = "";

            if (string.IsNullOrEmpty(url)) return "";

            try
            {
                // 创建Request请求
                var request = (HttpWebRequest)WebRequest.Create(url);

                // 提交POStT数据
                if (!string.IsNullOrEmpty(postData))
                {
                    request.Method = "POST";
                    request.ContentType = "application/json;charset=UTF-8";
                    request.Headers.Add("Authorization: Bearer " + API_KEY);

                    byte[] bytes = Encoding.UTF8.GetBytes(postData);

                    request.ContentLength = bytes.Length;

                    Stream stream = request.GetRequestStream();
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();
                }

                // 获取返回的响应结果
                try
                {
                    var response = (HttpWebResponse)request.GetResponse();
                    if (response != null)
                    {
                        Stream responseStream = response.GetResponseStream();

                        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                        result = reader.ReadToEnd();

                        reader.Close();
                        responseStream.Close();
                    }
                }
                catch (Exception)
                {
                    result = "4004, url对应的服务器，未返回响应信息！";
                }

            }
            catch (Exception ex)
            {
                result = ex.ToString();
                //result = "4003, url对应的服务器，不存在！";
            }

            return result;
        }

    }

}


